package com.hdoit.kylin.web.user.controllers;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.component.web.BaseController;

@Controller
@RequestMapping(value="/admin/user/upload/")
public class UploadAvatarController extends BaseController{
	@Override
	public String getRoutePath() {
		return "areas/admin/user/";
	}

	private final String uploadAvatarViewName="uploadAvatar";
	private final String avatarCropperViewName="avatarCropper";
	
	@RequestMapping(value=uploadAvatarViewName,method={RequestMethod.GET})
	public String uploadAvatar(){
		return view(uploadAvatarViewName);
	}
	
	@RequestMapping(value=uploadAvatarViewName,method={RequestMethod.POST})
	public String uploadAvatar(@RequestParam MultipartFile file, Model model,HttpServletRequest request)
					throws IOException{
		String message="";
		String result="failed";
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/content/images/avatar")+"/";
		if(file!=null){
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			
			if("jpg".equals(suffix)||"jepg".equals(suffix)||"png".equals(suffix)||"bmp".equals(suffix)||"gif".equals(suffix)){
				fileName=CommonUtils.getKeyId()+"."+suffix;
				file.transferTo(new File(path+fileName));
				
				result="success";
				message=fileName;
			}
		}
		
		model.addAttribute("result", result);
		model.addAttribute("message", message);
		
		return view(uploadAvatarViewName);
	}
	
	@RequestMapping(value=avatarCropperViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String avatarCropper(){
		return view(avatarCropperViewName);
	}
}
